package org.jeecgframework.web.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.ZyCinemaServiceI;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEquipmentChangeServiceI;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSRoleUser;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.ZyCinemaEntity;
import org.jeecgframework.web.system.pojo.base.ZyEquipmentChangeEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 设备变更申请
 * @author onlineGenerator
 * @date 2016-04-21 15:07:34
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/zyEquipmentChangeController")
public class ZyEquipmentChangeController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyEquipmentChangeController.class);

	@Autowired
	private ZyEquipmentChangeServiceI zyEquipmentChangeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCinemaServiceI zyCinemaService;
	@Autowired
	private ZyCommonService zyCommonService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 流程 - 工程师查看 巡检设备变更列表 页面跳转
	 * @return
	 */
	@RequestMapping(params = "zyEquipmentChange")
	public ModelAndView zyEquipmentChange(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_equipment_change/zyEquipmentChangeList");
	}

	/**
	 * @author xiul
	 * 2016-4-21 下午5:54:46
	 * Description 流程 - 工程师查看 巡检设备变更 列表 
	 */
	@RequestMapping(params = "datagrid")
	public void datagrid(ZyEquipmentChangeEntity zyEquipmentChange,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyEquipmentChangeEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEquipmentChange, request.getParameterMap());
		try{
			TSUser user = ResourceUtil.getSessionUserName();
			List<TSRoleUser> roleUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", user.getId());
			for (TSRoleUser tsRoleUser : roleUsers) {
				if(tsRoleUser.getTSRole().getRoleCode().equals(StaticValue.RULE_CODE_THIRDPARTY_HEADER)){
					//如果是第三方负责人 ，查询自己所属机构下的所有人提交的申请
					TSDepart depart = user.getCurrentDepart();
					if(null != depart){
						depart = zyCommonService.getUserRootTsDepartCode(depart);
						StringBuffer sql = new StringBuffer();
						sql.append(" SELECT ");
						sql.append(" 	ec.id ");
						sql.append(" FROM ");
						sql.append(" 	zy_equipment_change ec ");
						sql.append(" LEFT JOIN t_s_base_user bu ON ec.create_by = bu.username ");
						sql.append(" LEFT JOIN t_s_user_org uo ON bu.id = uo.user_id ");
						sql.append(" LEFT JOIN t_s_depart dp ON uo.org_id = dp.id ");
						sql.append(" WHERE ");
						sql.append(" 	dp.org_code LIKE '").append(depart.getOrgCode()).append("%' ");
						sql.append(" AND dp.logic_delete = 0 ");
						List<Map<String, Object>> mapList = systemService.findForJdbc(sql.toString());
						List<String> idList = new ArrayList<String>();
						for (Map<String, Object> map : mapList) {
							if(null != map){
								idList.add(StringUtil.isNotEmpty(map.get("id")) ? map.get("id").toString() : "");
							}
						}
						if(idList.size() == 0){
							//如果没有查询到所属机构下有人提交申请，那么集合给 add 一个空串（为了让列表查询不出数据，如果不add空串cq  in 一个长度为0的集合会报错）
							idList.add("");
						}
						cq.add(Restrictions.in("id", idList));
					}else{
						//如果 当前所属机构为 null （有可能登录时没有set进去。或者根本没配置），那么只查询自己的。（这种可能性极低）
						cq.add(Restrictions.eq("createBy", user.getUserName()));
					}
					break;//一定要break
				}else{
					//如果不是第三方负责人 ，只查询自己的申请
					cq.add(Restrictions.eq("createBy", user.getUserName()));
					break;//一定要break
				}
			}
			
//			List<String> idsList = zyWorkFlowService.queryUserProcess(user.getUserName(),StaticValue.P_PROCESS_EUQIPMENT_CHANGE,true,null);
//			if(idsList.size() == 0){
//				idsList.add("");
//			}
//			cq.add(Restrictions.in("id", idsList));
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyEquipmentChangeService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * zy_equipment_change新增页面跳转
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(ZyEquipmentChangeEntity zyEquipmentChange, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(zyEquipmentChange.getId())) {
			zyEquipmentChange = zyEquipmentChangeService.getEntity(ZyEquipmentChangeEntity.class, zyEquipmentChange.getId());
			req.setAttribute("zyEquipmentChangePage", zyEquipmentChange);
		}
		return new ModelAndView("com/zybk/zy_equipment_change/zyEquipmentChange-add");
	}

	/**
	 * @author xiul
	 * 2016-3-28 下午5:58:24
	 * Description 弹出式影院选择页 - 设备变更申请
	 */
	@RequestMapping(params = "zyChooseCinemasForEsChange")
	public ModelAndView zyChooseCinemasForEsChange(HttpServletRequest request) {
		return new ModelAndView("com/zybk/zy_equipment_change/zyEquipmentChangeChooseCinemas");
	}

	/**
	 * @author xiul
	 * 2016-4-21 下午4:39:29
	 * Description 弹出式影院选择页 datagrid
	 */
	@RequestMapping(params = "datagridOfChooseCinema")
	public void datagridOfChooseCinema(ZyCinemaEntity zyCinema,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyCinemaEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyCinema, request.getParameterMap());
		try{
			//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyCinemaService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * @author xiul
	 * 2016-4-21 下午5:54:07
	 * Description 流程 - 启动流程 添加变更申请  
	 * @param zyEquipmentChange
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(ZyEquipmentChangeEntity zyEquipmentChange, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		message = "设备变更申请添加成功";
		try{
			zyEquipmentChangeService.doStartProcess(zyEquipmentChange,null);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "设备变更申请添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	@ResponseBody
	@RequestMapping(params = "queryIpInfoByPlanId")
	public AjaxJson queryIpInfoByPlanId(HttpServletRequest req){
		AjaxJson j = new AjaxJson();
		try{
			zyEquipmentChangeService.queryIpInfoByPlanId(req, j);
		}catch(Exception e){
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * @author xiul
	 * 2016-4-21 下午5:51:11
	 * Description 流程 -巴可主管 巡检设备变更申请  审批页
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "zyEquipmentChangeApproval")
	public ModelAndView zyEquipmentChangeApproval(HttpServletRequest request) {
		request.setAttribute("states", StaticValue.DIC_EQ_REQ_STATE_NOT_APPROVAL);
		return new ModelAndView("com/zybk/zy_equipment_change/zyEquipmentChangeApprovalList");
	}

	/**
	 * @author xiul
	 * 2016-4-21 下午5:51:31
	 * Description 流程 - 巴可主管 巡检设备变更申请 审批页列表datagrid 
	 * @param zyEquipmentChange
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridOfApproval")
	public void datagridOfApproval(ZyEquipmentChangeEntity zyEquipmentChange,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyEquipmentChangeEntity.class, dataGrid);
		Map<String,String[]> params = new HashMap<String, String[]>();
		String paramOrgCode = "";
		params.putAll(request.getParameterMap());
		if(params.containsKey("inspectionCompany")){
			//防止系统默认加like"%P%" 查询 这里需要更改eq
			paramOrgCode = params.get("inspectionCompany")[0];
			if(StringUtil.isNotEmpty(paramOrgCode)){
				params.remove("inspectionCompany");
				cq.eq("inspectionCompany", paramOrgCode);
			}
		}
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEquipmentChange, params);
		try{
			//巴可 可以看见所有设备变更申请，所以不需要加 流程过滤
//			TSUser user = ResourceUtil.getSessionUserName();
//			List<String> idsList = zyWorkFlowService.queryUserProcess(user.getUserName(),StaticValue.P_PROCESS_EUQIPMENT_CHANGE,true,null);
//			if(idsList.size() == 0){
//				idsList.add("");
//			}
//			cq.add(Restrictions.in("id", idsList));
			cq.add();
			this.zyEquipmentChangeService.getDataGridReturn(cq, true);
			for (ZyEquipmentChangeEntity  zyEqChange: (List<ZyEquipmentChangeEntity>)dataGrid.getResults()) {
				if(zyEqChange != null){
					if(zyEqChange.getReqReasonType().equals(StaticValue.DIC_REQ_REASON_OTHERS)){
						//如果是其他原因，取其他原因存入 临时属性里
						zyEqChange.setReqReasonVal(zyEqChange.getReqOtherReason());
					}else{
						//否则直接取原因类型 存入 临时属性里
						zyEqChange.setReqReasonVal(zyEqChange.getReqReasonType());
					}
				}
			}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * @author xiul
	 * 2016-4-22 上午11:05:57
	 * Description 流程 - 跳转巴可主管 填写审批说明页 
	 */
	@RequestMapping(params="goApproval")
	public ModelAndView goApproval(HttpServletRequest request){
		String id = oConvertUtils.getString(request.getParameter("id"));
		String approvalFlag = oConvertUtils.getString(request.getParameter("approvalFlag"));
		request.setAttribute("id", id);
		request.setAttribute("approvalFlag", approvalFlag);
		return new ModelAndView("com/zybk/zy_equipment_change/zyEquipmentChangeApproval");
	}
	
	/**
	 * @author xiul
	 * 2016-4-22 上午11:05:43
	 * Description 流程 - 巴可主管做审批 
	 */
	@ResponseBody
	@RequestMapping(params="doApproval")
	public AjaxJson doApproval(HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		try {
			zyEquipmentChangeService.doApproval(request);
			message = "审批成功";
		} catch (Exception e) {
			j.setSuccess(false);
			message = "审批失败";
			e.printStackTrace();
		}
		j.setMsg(message);
		return j;
	}
	
	/**首页代办 - 巴可主管 待审批设备变更 - 页面跳转*/
	@RequestMapping(params = "zyEquipmentChangeApprovalOfHomePageTask")
	public ModelAndView zyEquipmentChangeApprovalOfHomePageTask(HttpServletRequest request) {
		String homePageType = oConvertUtils.getString(request.getParameter("homePageType"));
		request.setAttribute("homePageType", homePageType);
		request.setAttribute("states", StaticValue.DIC_EQ_REQ_STATE_NOT_APPROVAL);
		return new ModelAndView("com/zybk/zy_equipment_change/zyEquipmentChangeApprovalListOfHomePageTask");
	}
	/**首页代办 - 巴可主管 待审批设备变更 - datagrid*/
	@RequestMapping(params = "datagridOfApprovalOfHomePageTask")
	public void datagridOfApprovalOfHomePageTask(ZyEquipmentChangeEntity zyEquipmentChange,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyEquipmentChangeEntity.class, dataGrid);
		//查询条件组装器
		Map<String,String[]> params = new HashMap<String, String[]>();
		String paramOrgCode = "";
		params.putAll(request.getParameterMap());
		if(params.containsKey("inspectionCompany")){
			//防止系统默认加like"%P%" 查询 这里需要更改like规则 为 "P__" 意为 查询当前组织下的 02__
			paramOrgCode = params.get("inspectionCompany")[0];
			if(StringUtil.isNotEmpty(paramOrgCode)){
				params.remove("inspectionCompany");
				cq.like("inspectionCompany", paramOrgCode+"__");
			}
		}
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEquipmentChange, params);
		try{
			//如果是从首页进来的
			if(StringUtil.isNotEmpty(request.getParameter("homePageType"))){
				String homePageType = request.getParameter("homePageType");
				if(homePageType.equals("bsd_ipChange")){
					/*巡检设备变更待审批数量：巡检工程师提交设备变更（增加、减少、移机）后，还未审核的变更申请数量。*/
					cq.add(Restrictions.eq("approvalState", StaticValue.DIC_EQ_REQ_STATE_NOT_APPROVAL));
				}
			}
			cq.add();
			this.zyEquipmentChangeService.getDataGridReturn(cq, true);
			for (ZyEquipmentChangeEntity  zyEqChange: (List<ZyEquipmentChangeEntity>)dataGrid.getResults()) {
				if(zyEqChange != null){
					if(zyEqChange.getReqReasonType().equals(StaticValue.DIC_REQ_REASON_OTHERS)){
						//如果是其他原因，取其他原因存入 临时属性里
						zyEqChange.setReqReasonVal(zyEqChange.getReqOtherReason());
					}else{
						//否则直接取原因类型 存入 临时属性里
						zyEqChange.setReqReasonVal(zyEqChange.getReqReasonType());
					}
				}
			}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		TagUtil.datagrid(response, dataGrid);
	}
	/**首页代办 - 第三方 & 第三方工程师 设备变更 - 页面跳转*/
	@RequestMapping(params = "zyEsChangeOfHomePageTask")
	public ModelAndView zyEsChangeOfHomePageTask(HttpServletRequest request) {
		String homePageType = oConvertUtils.getString(request.getParameter("homePageType"));
		request.setAttribute("homePageType", homePageType);
		return new ModelAndView("com/zybk/zy_equipment_change/zyTpEsChangeListOfHomePageTask");
	}
	/**首页代办 - 第三方 & 第三方工程师  设备变更 - datagrid*/
	@RequestMapping(params = "datagridOfEsChangeOfHomePageTask")
	public void datagridOfEsChangeOfHomePageTask(ZyEquipmentChangeEntity zyEquipmentChange,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(ZyEquipmentChangeEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, zyEquipmentChange, request.getParameterMap());
		try{
			TSUser user = ResourceUtil.getSessionUserName();
			//从首页跳转过来
			String homePageType = request.getParameter("homePageType");
			TSDepart rootDepart = zyCommonService.getUserRootTsDepartCode(user.getCurrentDepart());//最上级组织（公司）
			String company = rootDepart.getOrgCode();
			if(homePageType.equals("th_ipChange")){
				/*巡检设备变更待审批数量：本公司的巡检工程师提交设备变更（增加、减少、移机）后，还未审核的变更申请数量。*/
				cq.add(Restrictions.like("inspectionCompany", company+"%"));
				cq.add(Restrictions.eq("approvalState", StaticValue.DIC_EQ_REQ_STATE_NOT_APPROVAL));
			}else if(homePageType.equals("te_ipChange")){
				/*未完成巡检计划数量：本人接受的巡检计划中没有提交巡检报告的数量。*/
				cq.add(Restrictions.eq("createBy", user.getUserName()));
				cq.add(Restrictions.eq("approvalState", StaticValue.DIC_EQ_REQ_STATE_NOT_APPROVAL));
			}
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.zyEquipmentChangeService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * @author xiul
	 * 2016-8-5 下午3:40:41
	 * Description APP - 我的申请 - 第三方商务 & 区域 & 普通工程师 
	 */
	@ResponseBody
	@RequestMapping(params="goAppEgEsChangeList")
	public AjaxJson goAppEgEsChangeList(HttpServletRequest req){
		AjaxJson j = new AjaxJson();
		List<Map<String, Object>> appEgEsChangeMapList = zyEquipmentChangeService.queryAppEgEsChangeListData();
		j.setObj(appEgEsChangeMapList);
		return j;
	}
	
	/**
	 * @author xiul
	 * 2016-8-8 上午10:03:39
	 * Description APP - 新增 设备变更申请  
	 */
	@ResponseBody
	@RequestMapping(params="appAddEsChange")
	public AjaxJson appAddEsChange(HttpServletRequest req){
		AjaxJson j = new AjaxJson();
		Map<String, Object> rtMap = new HashMap<String, Object>();
		List<Map<String, Object>> esChangeTypes = zyCommonService.queryTsTypesByTsTypegroupCode(StaticValue.DIC_EQ_CHANGE_TYPE);
		List<Map<String, Object>> esChangeReasons = zyCommonService.queryTsTypesByTsTypegroupCode(StaticValue.DIC_REQ_REASON);
		rtMap.put("esChangeTypes", esChangeTypes);
		rtMap.put("esChangeReasons", esChangeReasons);
		j.setAttributes(rtMap);
		return j;
//		req.setAttribute("esChangeTypes", esChangeTypes);
//		return new ModelAndView("com/app/cbs_equipment_change/appAddEgEsChange");
	}
	
	/**
	 * @author xiul
	 * 2016-8-8 下午6:33:14
	 * Description APP - 新增 设备变更申请 - 选择影院 
	 */
	@RequestMapping(params="appEsChangeChooseCm")
	public ModelAndView appEsChangeChooseCm(){
		return new ModelAndView("com/app/cbs_equipment_change/appEsChangeChooseCm-list");
	}
}

